package com.dahua.utils;

import java.io.IOException;

import org.apache.http.ParseException;
import org.json.JSONException;
import org.json.JSONObject;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

import com.dahua.db.DownloadInfo;
import com.dahua.download.DownLoadService;
import com.dahua.service.InstalllApkService;

public class VersionChecker {
    private Context context;
    private static final int MESSAGE_GET_VERSION_SUCCESS = 100;
    private static final int MESSAGE_NOT_NEED_UPDATE = 101;
    private static final long TEN_MINUTES = 1000 * 60 * 10;
    private String downloadUrl, versionName, description;
    private int versionCode;
    private Handler handler;
    private String path = Tool.getSDPath()
            + "/duhua/update/";

    public VersionChecker(Context context) {
        this.context = context;
    }

    public void startUpdate(String downloadUrl) {
        start(downloadUrl, path);
        // download(downloadUrl);
        // startService();
    }

    public void checkUpdate() {
        checkUpdate(false);
    }

    /**
     * 开始下载
     *
     * @param url
     * @param path
     */
    private void start(String url, String path) {
        Intent intent = new Intent(context, DownLoadService.class);
        intent.putExtra("url", url);
        intent.putExtra("path", path);
        intent.setAction("download");
        context.startService(intent);
    }

    /**
     * check update
     */
    public void checkUpdate(final boolean manual) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = ".Getversion.class.php";
                versionName = null;
                versionCode = -1;
                downloadUrl = null;
                try {
                    String res = Tool.postToServer(url, "key",
                            "C3CFC50E-E83B-4A7C-8ACD-D0C66A192CD6");
                    if (res == null) {
                        return;
                    }
                    System.out.println("version is: " + res);
                    if (res == null) {
                        return;
                    }
                    // {"versions":"1","downloadurl":null,"versions_name":"aaabscd","state":true}
                    JSONObject jo = new JSONObject(res);
                    boolean state = jo.getBoolean("state");
                    if (state) {
                        versionName = jo.getString("versions_name");
                        versionCode = jo.getInt("versions");
                        downloadUrl = jo.getString("downloadurl");
                        description = jo.getString("description");
                        System.out.println("description is: " + description);
                    }

                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (versionName == null || versionCode <= 0) {
                    // sendMessage(MESSAGE_GET_VERSION_FAIL, "获取版本号失败");
                    return;
                }
                // TODO: judge if need update
                if (Tool.getVersionCode(context) < versionCode) {
                    if (isDownloading()) {
                        return;
                    }
                    Message msg = new Message();
                    msg.what = MESSAGE_GET_VERSION_SUCCESS;
                    // msg.obj = downloadUrl;
                    handler.sendMessage(msg);
                } else if (manual) {
                    Message msg = new Message();
                    msg.what = MESSAGE_NOT_NEED_UPDATE;
                    // msg.obj = downloadUrl;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    private boolean isDownloading() {
        DownloadInfo info = new DownloadInfo(context).loadData();
        if (info.isDownloading()

                && System.currentTimeMillis() - info.getStartTime() < TEN_MINUTES) {
            return true;
        }
        return false;
    }

    private void update() {
        new AlertDialog.Builder(context).setTitle("有新版本发布")
                .setMessage(getMessage())
                .setPositiveButton("下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // download();
                        // startService();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    @SuppressLint("NewApi")
    private void download(String downloadUrl) {
        try {
            DownloadManager downloadManager = (DownloadManager) context
                    .getSystemService(Context.DOWNLOAD_SERVICE);
            Uri uri = Uri.parse(downloadUrl);
            Request request = new Request(uri);

            // 设置允许使用的网络类型，这里是移动网络和wifi都可以
            request.setAllowedNetworkTypes(Request.NETWORK_MOBILE
                    | Request.NETWORK_WIFI);

            // 禁止发出通知，既后台下载，如果要使用这一句必须声明一个权限：android.permission.DOWNLOAD_WITHOUT_NOTIFICATION
            // request.setShowRunningNotification(false);

            // 不显示下载界面
            request.setVisibleInDownloadsUi(false);
            /*
             * 设置下载后文件存放的位置,如果sdcard不可用，那么设置这个将报错，因此最好不设置如果sdcard可用，下载后的文件
             * 在/mnt/sdcard
             * /Android/data/packageName/files目录下面，如果sdcard不可用,设置了下面这个将报错
             * ，不设置，下载后的文件在/cache这个 目录下面
             */
            // request.setDestinationInExternalFilesDir(this, null, "tar.apk");
            long id = downloadManager.enqueue(request);
            // 把id保存好，在接收者里面要用，最好保存在Preferences里面
            new DownloadInfo(context).setId(id).setDownloading(true)
                    .setStartTime(System.currentTimeMillis()).saveData();
            ToastUtils.showToast(context, "Have been downloaded in the background!");
        } catch (Exception e) {
            ToastUtils.showToast(context, "Please download after installation!");
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(downloadUrl));
            context.startActivity(intent);
            // System.out.println(e);
        }
    }

    private void startService() {
        context.startService(new Intent(context, InstalllApkService.class));
    }

    private String getMessage() {
        StringBuffer sb = new StringBuffer();
        sb.append(versionName);
        sb.append("\n");
        sb.append(description);
        return sb.toString();
    }
}
